package prv.pursuivant.armory.impl;

import static org.mockito.Mockito.*;

import java.io.File;
import java.io.IOException;

import javax.xml.parsers.DocumentBuilderFactory;

import org.junit.Assert;
import org.w3c.dom.Document;

import prv.pursuivant.armory.Cache;
import prv.pursuivant.armory.DOMLeecher;
import prv.pursuivant.armory.DOMParser;
import prv.pursuivant.armory.Importer;
import prv.pursuivant.config.ImporterDesc;
import prv.pursuivant.config.impl.ImporterDescImpl;
import prv.pursuivant.core.ToonAchievements;
import prv.pursuivant.core.impl.CategoryAchievType;
import prv.pursuivant.core.impl.ToonImpl;

import com.google.inject.AbstractModule;
import com.google.inject.Guice;
import com.google.inject.Injector;

public class ArmoryImporterFunctionalTest {

	private static final class MyModule extends AbstractModule {
		@Override
		protected void configure() {
			DOMLeecher mockedLeecher = prepareLeecherMock();
			CategoryAchievType mockedCategory = prepareCategoryMock();
			bind(Importer.class).to(ArmoryImporter.class);
			bind(Cache.class).to(XStreamCache.class);
			bind(DOMParser.class).to(DOMParserImpl.class);
			bind(DOMLeecher.class).toInstance(mockedLeecher);
			bind(CategoryAchievType.class).toInstance(mockedCategory);
			bind(ImporterDesc.class)
					.toInstance(
							new ImporterDescImpl("eu", "Shadowsong",
									"testWD/cache", 0));
		}

		private CategoryAchievType prepareCategoryMock() {
			CategoryAchievType mockedCategory = mock(CategoryAchievType.class);
			when(mockedCategory.getId()).thenReturn("168");
			return mockedCategory;
		}

		private DOMLeecher prepareLeecherMock() {
			DOMLeecher mockedLeecher = mock(DOMLeecher.class);
			try {
				final Document kwintoXML = DocumentBuilderFactory
						.newInstance()
						.newDocumentBuilder()
						.parse(
								new File(
										"testWD/armoryData/Kwinto-preUlduar.xml"));
				when(mockedLeecher.getDOM("Kwinto")).thenReturn(kwintoXML);
			} catch (Exception e) {
				throw new RuntimeException(e);
			}
			return mockedLeecher;
		}
	}

	/**
	 * @param args
	 * @throws IOException
	 */
	public static void main(String[] args) throws IOException {
		Injector injector = Guice.createInjector(new MyModule());
		Importer importer = injector.getInstance(Importer.class);
		new ArmoryImporterFunctionalTest(importer).testKwinto();
	}

	private ArmoryImporterFunctionalTest(Importer importer) {
		this.importer = importer;
	}

	private final Importer importer;

	private void testKwinto() throws IOException {
		ToonAchievements achievements = importer.readAchievements(new ToonImpl(
				"Kwinto", 3));
		Assert.assertTrue(achievements.contains("1112"));
	}
}
